// returnnpc.txt
// Like basicnpc, except placed to defend an area. If circumstances make it go farther than 
// n spaces from its start position, it goes back. Never fidgets
// Memory Cells:
//   Cell 0 - Unused.
//   Cell 1,2 - Stuff done flag. If both 0, nothing. Otherwise when this is killed, inc by 1.
//   Cell 3 - Personality
//   Cell 4 - Distance is returns from. 
//       Can't be less than 9 (because then monst will target things it can't attack).

begincreaturescript;

variables;

short i,target;
short return_dist = 9;

body;

beginstate INIT_STATE;
	if (get_memory_cell(4) > 0)
		return_dist = get_memory_cell(4);
	if (return_dist < 9)
		return_dist = 9;
	break;

beginstate DEAD_STATE;
	if ((get_memory_cell(1) != 0) || (get_memory_cell(2) != 0))
		inc_flag(get_memory_cell(1),get_memory_cell(2),1);
break;

beginstate START_STATE; 
	if (my_dist_from_start() >= return_dist) 
		return_to_start(ME,2);

	// if I have a target for some reason, go attack it
	if (target_ok()) {
		if (dist_to_char(get_target()) <= 16)
			set_state(3);
			else set_foe_target(ME,-1);
		}
	
	if (get_foe_target(ME,8,0)) {
		do_attack();
		set_state(3);
		}
	if (who_shot_me() >= 0) {
		set_foe_target(ME,who_shot_me());
		do_attack();
		set_state(3);
		}

	if (am_i_doing_action() == FALSE)
		end_combat_turn();
break;

beginstate 3; // attacking
	if (target_ok() == FALSE)
		set_state(START_STATE);

	if (my_dist_from_start() >= return_dist) {
		set_foe_target(ME,-1);
		return_to_start(ME,2);
		set_state(START_STATE);
		}

	do_attack();
break;

beginstate TALKING_STATE;
	if (get_memory_cell(3) == 0) {
		print_str("Talking: It doesn't respond.");
		}
		else begin_talk_mode(get_memory_cell(3));
break;